use crate::conf::locad_conf::Config as conf;
use crate::wdlog::log;
use std::collections::HashMap;

use crate::app::handle::core;
use crate::app::handle::validation;
use crate::app::module::db;
use crate::app::module::rooms;
use crate::app::server;
use crate::cmd::flag::parse;

pub fn log_init() {
    log::set_file_line(true);
    log::set_level(log::DEBUG);
    log::set_prefix(String::new());
    log::set_time_print(false);
    // log::output_to_file("./log.txt").unwrap();
}
pub fn load_config(ft: &parse::FlagTree) -> conf {
    let path: &'static str = match ft.flags.get("-c") {
        None => "./src/conf/config.toml",
        Some(e) => Box::leak(e.value.clone().into_boxed_str()),
    };
    log_panic_result!(conf::new(path))
}
pub fn run(_: HashMap<String, String>, pf: &parse::FlagTree) -> Result<(), String> {
    //加载配置文件
    let config = load_config(pf);
    //初始化日志
    log_init();
    //连接数据库
    // db::db_init(config.db.pg_url, config.db.max_conn);
    db::db_pool_init (config.db.pg_url, config.db.max_conn as usize);
    //初始化房间
    rooms::init_room(config.rooms.room_count,config.rooms.room_size);
    //初始化验证系统
    validation::init_email(
        config.email.host.clone(),
        config.email.port.clone(),
        config.email.smtp_user.clone(),
        config.email.smtp_pawd.clone(),
    );
    //启动服务
    log_info_ln!("{}", "服务开始启动");
    let mut se = server::entity::ServerEntity::new(config.server.addr_and_port);
    core::init_call_register(&mut se);
    match se.run() {
        Ok(_) => Ok(()),
        Err(e) => Err(e.to_string()),
    }
}
